import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Video } from 'src/entities/video.entity';
import { User } from 'src/entities/user.entity';
import { SearchParamsDto, SortOrder } from './dto/search-params.dto';
import { VideoService } from '../video/video.service';

@Injectable()
export class SearchService {
  constructor(
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private videoService: VideoService,
  ) {}

  /**
   * 搜索视频
   */
  async searchVideos(params: SearchParamsDto, currentUserId?: number) {
    const { keyword, page, limit, sort } = params;
    const skip = (page - 1) * limit;

    // 创建查询构建器
    const queryBuilder = this.videoRepository
      .createQueryBuilder('video')
      .leftJoinAndSelect('video.user', 'user')
      .leftJoinAndSelect('video.category', 'category')
      .where('video.is_delete = 0')
      .andWhere('video.status = :status', { status: 'approved' });

    // 关键词搜索
    if (keyword) {
      queryBuilder.andWhere(
        '(video.title LIKE :keyword OR video.description LIKE :keyword)',
        { keyword: `%${keyword}%` },
      );
    }

    // 排序规则
    switch (sort) {
      case SortOrder.POPULAR:
        queryBuilder.orderBy('video.likes_count', 'DESC');
        break;
      case SortOrder.LATEST:
        queryBuilder.orderBy('video.created_at', 'DESC');
        break;
      case SortOrder.RELEVANCE:
      default:
        queryBuilder.orderBy('video.likes_count', 'DESC');
    }

    // 分页
    queryBuilder.skip(skip).take(limit);

    // 执行查询
    const [videos, total] = await queryBuilder.getManyAndCount();

    // 处理结果
    const enhancedVideos = videos.map((video) => {
      // 处理视频作者信息，移除敏感字段
      if (video.user) {
        const { password, ...safeUser } = video.user;
        video.user = safeUser as User;
      }

      // 这里可以添加额外的处理，例如检查当前用户是否点赞过该视频等
      return video;
    });

    return {
      data: enhancedVideos,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    };
  }
  /**
   * 搜索用户
   */
  async searchUsers(params: SearchParamsDto, currentUserId?: number) {
    const { keyword, page, limit, sort } = params;
    const skip = (page - 1) * limit;

    // 创建查询构建器
    const queryBuilder = this.userRepository
      .createQueryBuilder('user')
      .where('user.is_delete = 0');

    // 关键词搜索
    if (keyword) {
      queryBuilder.andWhere(
        '(user.username LIKE :keyword OR user.bio LIKE :keyword)',
        { keyword: `%${keyword}%` },
      );
    }

    // 排序规则
    switch (sort) {
      case SortOrder.POPULAR:
        queryBuilder.orderBy('user.follower_count', 'DESC');
        break;
      case SortOrder.LATEST:
        queryBuilder.orderBy('user.created_at', 'DESC');
        break;
      case SortOrder.RELEVANCE:
      default:
        queryBuilder
          .orderBy(
            `CASE 
            WHEN user.username LIKE :exactMatch THEN 10
            WHEN user.username LIKE :startMatch THEN 8
            WHEN user.username LIKE :containMatch THEN 5
            WHEN user.bio LIKE :containMatch THEN 3
            ELSE 0 
          END`,
            'DESC',
          )
          .addOrderBy('user.follower_count', 'DESC')
          .setParameter('exactMatch', keyword)
          .setParameter('startMatch', `${keyword}%`)
          .setParameter('containMatch', `%${keyword}%`);
    }

    // 分页
    queryBuilder.skip(skip).take(limit);

    // 执行查询
    const [users, total] = await queryBuilder.getManyAndCount();

    // 处理结果，如检查当前用户是否关注了这些用户
    const enhancedUsers = users.map((user) => {
      // 移除敏感信息
      const { password, ...safeUser } = user;
      return {
        ...safeUser,
        // 如果需要，这里可以添加是否关注等信息
      };
    });

    return {
      data: enhancedUsers,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    };
  }
}
